package com.neu.flashmall.ms.controller;

import com.neu.common.utils.Result;
import com.neu.common.valid.AddGroup;
import com.neu.flashmall.ms.entity.SysRole;
import com.neu.flashmall.ms.service.SysRoleService;
import com.neu.flashmall.ms.vo.RoleVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(value = "/sysRole")
@Api(value = "系统用户类型Controller")
public class SysRoleController {
    @Resource
    private SysRoleService sysRoleService;

    @GetMapping(value = "/getAllRole")
    @ApiOperation(value = "获取所有的角色以及角色包含的权限信息，不包含权限类型树")
    public Result getAllRole() throws CloneNotSupportedException {
        List<RoleVo> result = sysRoleService.getAllRoleWithoutSysMenuVo();
        return Result.ok().put(result);
    }

    @GetMapping(value = "/getAllRoleWithoutAuthority")
    @ApiOperation(value = "获取所有的角色不包含其他任何信息")
    public Result getAllRoleWithoutAuthority() throws CloneNotSupportedException {
        List<SysRole> sysRoleList = this.sysRoleService.getAllRoleOnly();
        return Result.ok().put(sysRoleList);
    }

    @DeleteMapping(value = "/check/deleteRoleInfo")
    @ApiOperation("通过role的id来删除role，已经删除role_menu表中的数据")
    public Result deleteRoleInfo(Long roleId){
        String outcome = this.sysRoleService.deleteRoleInfo(roleId);
        if(outcome.equals("删除用户类型成功")){
            return Result.ok().setMessage(outcome);
        }
        return Result.error().setMessage(outcome);
    }

    @PutMapping(value = "/check/addRole")
    @ApiOperation("添加用户类型")
    public Result deleteRoleInfo(
            @RequestBody @Validated(AddGroup.class) SysRole sysRole,
            BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String error = bindingResult.getFieldErrors().get(0).getField() + ":"
                    + bindingResult.getFieldErrors().get(0).getDefaultMessage();
            return Result.error().setMessage(error);
        }
        String result = this.sysRoleService.addRole(sysRole);
        if("添加用户类型成功".equals(result)){
            return Result.ok().setMessage(result).put(sysRole);
        }
        return Result.error().setMessage(result);
    }
}
